
#include "mqPool.h"
#include <iostream>
using namespace std;

void *func_do(void *)
{
	pthread_t tid = pthread_self();
	MqPool *p = MqPool::Instance();
	if(p!= NULL)
	{
		MYSQL  *conn = NULL;
		int fId = 0; 
		conn = p->GetWriter(fId, 0);
		if(conn == NULL)
		{
			p->CloseWriter(fId, conn);
			ERRO <<tid<< ": can't get connection!"<<endl;
			return NULL;
		}
                const char *sql="select * from guid";
		if(mysql_real_query(conn, sql, strlen(sql) ) == 0){
			MYSQL_RES *result = mysql_store_result(conn);
			if(result != NULL){
				long rownum = mysql_num_rows(result);
				if (rownum <= 0 )
				{
					mysql_free_result(result);
					p->CloseWriter(fId, conn);
					return NULL;
				}
				MYSQL_ROW row;
				while((row = mysql_fetch_row(result)))
					cout<<tid<<" :"<<(char *)row[0]<< endl;
			}
		}
		else
		{     ERRO <<tid<<" :"<< mysql_error(conn) << endl; }
		p->CloseWriter(fId, conn);
	}
        return NULL;
}

void *func(void *)
{
	int i=0;
	while(i<50)
	{
		func_do(NULL);
		usleep(2);
                i++;
	}
        return NULL;
}

pthread_t create_worker()
{
    pthread_t       thread;
    pthread_attr_t  attr;
    int             ret;
    pthread_attr_init(&attr);
    if((ret = pthread_create(&thread, &attr, func,NULL)) != 0) {
            fprintf(stderr, "Can't create thread: %s\n",
                            strerror(ret));
            exit(1);
    }
    cout<<"create pthread_id ="<<thread<<endl;
    return thread;
}

int main(int argc, char* argv[])
{
	if(argc < 2)
	{
		cout<<argv[0]<<" conf"<<endl;
		return 0;
	}
	MqPool *p = MqPool::Instance(argv[1]);
	if(p!= NULL)
	{
		MYSQL  *conn = NULL;
		int fId = 0; 
		conn = p->GetWriter(fId, 0);
		if(conn == NULL)
		{
			p->CloseWriter(fId, conn);
			ERRO <<tid<< ": can't get connection!"<<endl;
			return NULL;
		}
		const char *sql="select uuid from guid where id=1";
		if(mysql_real_query(conn, sql, strlen(sql) ) == 0){
			MYSQL_RES *result = mysql_store_result(conn);
			if(result != NULL){
				long rownum = mysql_num_rows(result);
				if (rownum > 0 )
				{
					MYSQL_ROW row;
					if((row = mysql_fetch_row(result)))
					{	
                                            //cout<<tid<<" :"<<(char *)row[0]<< endl; 
                                        }
				}
				mysql_free_result(result);
			}
		}
		else
		{     ERRO <<tid<<" :"<< mysql_error(conn) << endl; }
		p->CloseWriter(fId, conn);
	}
/*
	const int NUM = 3;
	pthread_t pt[NUM]  ;
	for(int i=0;i< NUM;i++)
		pt[i] = create_worker();
	for(int i=0;i< NUM;i++)
		pthread_join( pt[i] , NULL);
	cout<<"This is the main process."<<endl;
*/
	if(p!= NULL)
		MqPool::Release();

	return 0;
}

